'''
module
'''

from urllib import request
import ssl
import re
ssl._create_default_https_context = ssl._create_unverified_context


class Spider():
    # https://www.panda.tv/cate/qqfc?pdt=1.24.s1.64.7p9liv3daj3
    url = 'https://www.panda.tv/cate/lol'
    root_pattern = 'div class="video-info">([\s\S]*?)</div>'
    nickname_pattern = '<span class="video-nickname" title="([\s\S]*?)">'
    number_pattern = '<span class="video-number"><i class="ricon ricon-eye"></i>([\s\S]*?)</span>'
    # get content

    def __fetch_content(self):
        r = request.urlopen(Spider.url)
        htmls = r.read()
        htmls = str(htmls, encoding='utf-8')
        return htmls
    # analysis conteng for html

    def __analysis(self, htmls):
        root_html = re.findall(Spider.root_pattern, htmls)
        anchors = []
        for html in root_html:
            name = re.findall(Spider.nickname_pattern, html)
            number = re.findall(Spider.number_pattern, html)
            anchor = {'name': name, 'number': number}
            anchors.append(anchor)
        return anchors

    def __refine(self, anchors):
        #l=lambda anchor:{'name':anchor['name'][0].strip()}
        def l(anchor): return {
            'name': anchor['name'][0].strip(),
            'number': anchor['number'][0]
        }
        return map(l, anchors)

    def __sourt(self, anchors):
        anchors = sorted(anchors, key=self.__sort_seed, reverse=True)
        return anchors

    def __sort_seed(self, anchor):
        r = re.findall('\d*', anchor['number'])
        number = float(r[0])
        if '万' in anchor['number']:
            number *= 10000
        return number

    def __show(self, anchors):
        for rank in range(0, len(anchors)):
            print('【排名'+str(rank+1)
                  + '】\t\t【主播名'+anchors[rank]['name']
                  + '】\t\t【关注人数'+anchors[rank]['number']+'】'
                  )
           # print('rank': str(rank+1) + ':'anchors[rank]['name'] + '  '+anchors[rank]['number'])

    def go(self):
        htmls = self.__fetch_content()
        anchors = self.__analysis(htmls)
        anchors = list(self.__refine(anchors))
        anchors = self.__sourt(anchors)
        self.__show(anchors)


spider = Spider()
spider.go()


# \w 单词字符 \W
# \s 空白字符 \S
# .匹配除换行符\n之外其他所有字符
